/*
 * @Description: 系统通知相关
 */
import { onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import mitt from '@/mitt/index'
import { useMessage, useNotification, useLoadingBar } from 'naive-ui'

let currentMsg = ''
let currentContent = ''

export default function () {
  const router = useRouter()
  const message = useMessage()
  const notification = useNotification()
  const loadingBar = useLoadingBar()
  const { t } = useI18n()
  // 权限校验未通过通知
  mitt.on('permissionCheckError', () => {
    message.error(t('system.loginTip'))
    router.push('/login')
  })
  // message通知
  mitt.on('messageTip', ({ type, msg, useTranslate = false }) => {
    if (currentMsg == msg) {
      setTimeout(() => {
        currentMsg = ''
      }, 1000)
      return
    }
    currentMsg = msg
    useTranslate ? message[type](t(msg)) : message[type](msg)
  })
  // notify通知
  mitt.on(
    'notify',
    ({
      type = 'success',
      content = t('system.searchNullResult'),
      title = t('system.systemNotice'),
      duration = 3500
    }) => {
      if (currentContent == content) {
        setTimeout(() => {
          currentContent = ''
        }, 1000)
        return
      }
      currentContent = content
      notification[type]({
        content,
        title,
        duration,
        keepAliveOnHover: true
      })
    }
  )

  // 进度条开始
  mitt.on('loadingStart', () => {
    loadingBar.start()
  })
  // 进度条结束
  mitt.on('loadingFinish', () => {
    loadingBar.finish()
  })

  onBeforeUnmount(() => {
    mitt.off('permissionCheckError')
    mitt.off('message')
    mitt.off('notify')
  })
}
